package com.cloudRestudy.customer.controller;

import com.cloudRestudy.common.core.result.R;
import com.cloudRestudy.customer.feign.RemoteHystrixService;
import lombok.AllArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @ClassName : CustomerController
 * @Author : lby
 * @Date: 2021/7/19 14:20
 * @Description : Rest远程调用
 */
@RestController
@RequestMapping("customer")
@AllArgsConstructor
public class CustomerController {
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;
    private final RemoteHystrixService remoteHystrixService;
    /**
     * 使用自定义的负载均衡算法
     *
     */
//    private final MyRibbonRule myRibbonRule;


    /**
     * customer 远程调用 payment
     * @return
     */
    @GetMapping("/user-list")
    public R testRemoteCall(){
        R userList = restTemplate.getForObject("http://cloud-payment/user/list", R.class);
        return userList;
    }


    @GetMapping("/user-list/entity")
    public R testRemoteCall01(){
        // 这个forEntity 就相当于一个httpGET请求
        ResponseEntity<R> forEntity = restTemplate.getForEntity("http://cloud-payment/user/list", R.class);
        return  forEntity.getBody();
    }

//
//    @GetMapping("/my-ribbon-rule")
//    public R testMyRibbonRule(){
//        // 获取当前注册中心全部可用的服务个数
//        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT");
//        if (instances==null || instances.size()==0){
//            return R.failed("当前可用服务数量为0");
//        }
//        // 通过自定义的算法选择一个使用的服务
//        ServiceInstance allInstances = myRibbonRule.getAllInstances(instances);
//        // 访问地址
//        URI uri = allInstances.getUri();
//        return restTemplate.getForObject(uri+"/user/list",R.class);
//    }



    @GetMapping("/success-msg")
    public R getSuccessMsg(){
        return  remoteHystrixService.getSuccessMsg();
    }



    @GetMapping("/error-msg")
    public R getErrorMsg(){
        return  remoteHystrixService.getErrorMsg();
    }
}
